package com.meixiang.activity.account.myAppointment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.personalCenter.AllAppointmentAdapter;
import com.meixiang.entity.servicOrder.AllServiceOrderResult;
import com.meixiang.entity.servicOrder.ServiceRefundResult;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.TitleView;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author xyj  Created at 2016/5/6 13:42
 */
public class MyAllAppointmentActivity extends BaseActivity implements OnRefreshListener,OnLoadMoreListener{
    @Bind(R.id.title)
    TitleView titleView ; //头部视图
    @Bind(R.id.swipe_target)
    RecyclerView mRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mLayout ;
    private AllAppointmentAdapter appointmentAdapter;
    private String orderStatus ,orderState; //订单状态: //10:待付款;/ 30:待使用;/ 40:待评价/交易完成 不填默认查询全部订单
    private int pageNo = 1, pageSize  = 10; //当前页和每页显示的条数
    private List<AllServiceOrderResult.ServiceOrderGoodsList> list ;
    private List<ServiceRefundResult.RefundList> refundList ;
    private AllServiceOrderResult orderDetails ;
    private ServiceRefundResult refundResult ;
    private boolean isLoadMore = false;
    private int totalPage;
    private DetailBroadCast broadCast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_all_appointment);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        registerBroadCast();
    }

    @Override
    protected void initTitle() {
        titleView.setTitle(R.string.appointment_all_data);
        titleView.setLeftImageButton(R.mipmap.back);
        titleView.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        orderStatus=getIntent().getStringExtra("status");
        if(!AbStrUtil.isEmpty(orderStatus)){
            setTitle(orderStatus);
        }

    }

    @Override
    protected void initView() {
        mLayout.setOnLoadMoreListener(this);
        mLayout.setOnRefreshListener(this);
        appointmentAdapter=new AllAppointmentAdapter(context,orderStatus,MyAllAppointmentActivity.this);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycler.setLayoutManager(linearLayoutManager);
        mRecycler.setAdapter(appointmentAdapter);
    }

    /**
     * orderState 	String 	必填 	10 		:订单状态 //10:待付款;/ 30:待收货;/ 40:待评价/交易完成
     * pageSize 	String 	必填 	10 	10 	每页大小
     * pageNo
     */
    private void getData() {
        if(isLoadMore==false){
            status.showLoading();
        }
        if (!AbStrUtil.isEmpty(orderStatus)) {
            if ("待付款".equals(orderStatus)) {
                orderState = "10";
            } else if ("待使用".equals(orderStatus)) {
                orderState = "30";
            } else if ("待评价".equals(orderStatus) || ("退款/售后").equals(orderStatus)) {
                orderState = "40";
            }
        }
        String url;
        HttpParams params = null ;
        if("退款/售后".equals(orderStatus)){
            params = new HttpParams();
            params.put("pageSize",String.valueOf(pageSize));
            params.put("pageNo",String.valueOf(pageNo));
            url = Config.SERVICE_ORDER_REFUND_LIST ;
        }else{
            url = Config.GET_MY_ALL_SERVICE_ORDER ;
            params = new HttpParams();
            params.put("orderState", orderState);
            params.put("pageSize", String.valueOf(pageSize));
            params.put("pageNo", String.valueOf(pageNo));
        }
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                onCompleteRefresh();
                Log.i("result","result ="+result.toString());
                if(result.toString()!=null&&!"".equals(result.toString())&&!"{}".equals(result.toString())){
                    totalPage=result.optInt("totalPage");
                    if(totalPage==0){
                        status.showNoData("你还没有相关的订单");
                    }
                    if("退款/售后".equals(orderStatus)){
                        refundResult = AbJsonUtil.fromJson(result.toString(),new TypeToken<ServiceRefundResult>(){});
                        if(refundResult !=null && refundResult.getRefundList().size()!=0){
                            if(isLoadMore){ //表示上啦加载更多数据
                                // 退款列表数据
                                refundList.addAll(refundResult.getRefundList());
                                appointmentAdapter.refreshRefundData(refundResult.getRefundList());
                            }else{
                                refundList = refundResult.getRefundList() ;
                                appointmentAdapter.refreshRefundData(refundResult.getRefundList());
                            }
                        }
                    }else{
                        orderDetails = AbJsonUtil.fromJson(result.toString(), new TypeToken<AllServiceOrderResult>() {
                        });
                        if(orderDetails !=null && orderDetails.getList().size()!=0){
                            if(isLoadMore){ //表示上啦加载更多数据
                                list.addAll(orderDetails.getList());
                                appointmentAdapter.refreshData(list);
                            }else{
                                list = orderDetails.getList() ;
                                appointmentAdapter.refreshData(list);
                            }
                        }
                    }

                }else{
                    status.showNoData("你还没有相关的订单");
                }

            }

            @Override
            public void onError(String code, String message) {
                onCompleteRefresh();
                Tool.showTextToast(context, message);
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLayout.setRefreshing(true);
                    }
                });
            }
        });
    }

    private class DetailBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
//            String orderId = intent.getStringExtra("orderId");
            mLayout.setRefreshing(true);
        }
    }

    private void registerBroadCast(){
        broadCast=new DetailBroadCast();
        IntentFilter intentFilter=new IntentFilter(GlobalType.APPOINTMENT_DETIAL);
        registerReceiver(broadCast,intentFilter);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!MXApplication.mApp.hasLogin()) {
            getData();
        }
    }

    @Override
    protected void setData() {
        getData();
    }

    @Override
    public void onClick(View v) {

    }

    private void onCompleteRefresh() {
        status.removeView();
        if (mLayout != null) {
            if (isLoadMore) {
                mLayout.setLoadingMore(false);
            } else {
                mLayout.setRefreshing(false);
            }
        }
    }

    @Override
    public void onLoadMore() {
        isLoadMore = true ;
        pageNo ++ ;
        if(pageNo>totalPage){ //如果当前页大于总页数则表示无更多数据
            mLayout.setLoadingMore(false);
            AbToastUtil.showToast(context,"暂无更多数据");
            return;
        }
        getData();
    }

    @Override
    public void onRefresh() {
        isLoadMore = false ;
        pageNo = 1 ;
        getData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        unregisterReceiver(broadCast);
    }
}
